Unique word abbreviation¶
Time: ctor:O(N),lookup:O(1); Space: O(K); easy
An abbreviation of a word follows the form < first letter > < number > < last letter >.
Below are some examples of word abbreviations:
a) it --> it (no abbreviation)
1
b) d|o|g --> d1g
1 1 1
1---5----0----5--8
c) i|nternationalizatio|n --> i18n
1
1---5----0
d) l|ocalizatio|n --> l10n
Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary.
A word’s abbreviation is unique if no other word from the dictionary has the same abbreviation.
Example 1:
Input: dictionary = {ValidWordAbbr} [“deer”, “door”, “cake”, “card”], word = “dear”
Output: False
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“dear” ’s abbreviation is “d2r” , in dictionary.
Example 2:
Input: dictionary = {ValidWordAbbr} [“deer”, “door”, “cake”, “card”], word = “card”
Output: True
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“cart” ’s abbreviation is “c2t” , not in dictionary.
Example 3:
Input: dictionary = {ValidWordAbbr} [“deer”, “door”, “cake”, “card”], word = “cane”
Output: False
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“cane” ’s abbreviation is “c2e” , in dictionary.
Example 4:
Input: dictionary = {ValidWordAbbr} [“deer”, “door”, “cake”, “card”], word = “make”
Output: True
Explanation:
Dictionary’s abbreviation is [“d2r”, “d2r”, “c2e”, “c2d”].
“make” ’s abbreviation is “m2e” , not in dictionary.
[1]:
import collections
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str]
"""
self.lookup_ = collections.defaultdict(set)
for word in dictionary:
abbr = self.abbreviation(word)
self.lookup_[abbr].add(word)
def isUnique(self, word):
"""
check if a word is unique.
:type word: str
:rtype: bool
"""
abbr = self.abbreviation(word)
return self.lookup_[abbr] <= {word}
def abbreviation(self, word):
if len(word) <= 2:
return word
return word[0] + str(len(word)-2) + word[-1]
[2]:
dictionary = ["deer", "door", "cake", "card"]
s = ValidWordAbbr(dictionary)
word = "dear"
assert s.isUnique( word) == False
word = "card"
assert s.isUnique( word) == True
word = "cane"
assert s.isUnique( word) == False
word = "make"
assert s.isUnique( word) == True